const { Service, start } = require("egg");

class BlogService extends Service {
    async addBlog(body) {
        try {
            const Blog = {
                title: body.title,
                img: body.img,
                md_text: body.md_text,
                html_text: body.html_text
            }
            await this.app.model.Blog.create(Blog)
            return true
        } catch (error) {
            return false
        }
    }
    async getBlog(query) {
        try {
            let id = query.id;
            if(id){
                return await this.app.model.Blog.findOne({
                    where:{
                        id
                    }
                })
            }else{
                let number = parseInt(query.page)
                let start = number*10-10
                let total = parseInt(query.total)
                return await this.app.model.Blog.findAll({
                    limit:[start,total]
                })
            }
        } catch (error) {
            return null
        }
    }
    async deleteBlog(id) {
        try {
            await this.app.model.Blog.destroy({
                where: {
                    id
                }
            })
            return true
        } catch (error) {
            return false
        }
    }
    async updateBlog(id, body) {
        try {
            const blog = {
                title: body.title,
                img: body.img,
                md_text: body.md_text,
                html_text: body.html_text
            }
            await this.ctx.model.Blog.update(blog, {
                where: {
                    id
                }
            })
            return true
        } catch (error) {
            return false
        }
    }
    async getBlogDetail(id){
        try {
           const blog =  await this.app.model.Blog.findOne({
                where: {
                    id
                }
            })
            return blog
        } catch (error) {
            return false
        }
    }
}

module.exports = BlogService